package com.neteast.androidclient.contact.activity;

import java.net.URL;
import java.util.Timer;
import java.util.TimerTask;
import org.xmlpull.v1.XmlPullParser;
import com.neteast.androidclient.contact.R;
import com.neteast.androidclient.contact.service.DownLoadService;
import com.neteast.androidclient.contact.util.LoginUtil;
import com.neteast.androidclient.contact.util.NetUtil;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class VerificationPhoneActivity extends Activity implements
		OnClickListener {
	private SharedPreferences sharedPreferences;
	private EditText phoneNum, verificationCode;
	private Button btnGetCode, btnLogin;
	private Timer timer;
	private int waitTime = 10;
	private final String SP_NAME = "verification_info";
	private Context mContext;
	
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case UPDATE_TIME:
				btnGetCode.setText(waitTime + "秒后可重发");
				waitTime--;
				if (waitTime <= 0) {
					waitTime = 10;
					btnGetCode.setText("");
					btnGetCode.setEnabled(true);
					btnGetCode
							.setBackgroundResource(R.drawable.btn_get_code_bg);
					timer.cancel();
					timer = null;
				}
				break;
			case NEED_UPGRADE:
				showAppUploadWindow();
				break;
			case DO_NOT_NEED_UPGRADE:
				checkLoginState();
				break;
			case UPGRADE_ERROR:
				if (info!=null&&info.must) {
					finish();
				}else {
					Toast.makeText(mContext, "获取升级信息失败", Toast.LENGTH_SHORT).show();
					checkLoginState();
				}
				break;
			}
		}

	};
	private AlertDialog loginDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.verification_phone);
		mContext = VerificationPhoneActivity.this;
		findView();
		if(!NetUtil.netIsValidate(mContext)){
			Toast.makeText(VerificationPhoneActivity.this, "当前无网络可用，请确认网络链接正常",
					Toast.LENGTH_LONG).show();
		}
		sharedPreferences = getSharedPreferences(SP_NAME, Activity.MODE_PRIVATE);
		refreshUploadInfo("http://218.108.168.46:8888/contacts/upgrade.xml");
	}
	/**
	 * 检查登录状态
	 */
	private void checkLoginState() {
		Uri uri = Uri.parse("content://com.neteast.androidclient.newscenter/info");
		Cursor cursor = getContentResolver().query(uri, null, null, null, null);
		if(cursor != null){
			if (cursor.moveToFirst()) {
				int userid = cursor.getInt(cursor.getColumnIndex("userid"));
				String token = cursor.getString(cursor.getColumnIndex("token"));
				Log.i("test", "userid="+userid);
				Log.i("test", "token="+token);
				//登录
				if (userid>0) {
					LoginUtil.setLastLoginUserId(mContext, userid);
					LoginUtil.setLastLoginToken(mContext, token);
					if (sharedPreferences.getBoolean("isVerificated", false)) {
						startActivity(new Intent(VerificationPhoneActivity.this,
								MainActivity.class));
						finish();
					}
					return;
				}
			}
			loginDialog.show();
		}else{
			Toast.makeText(mContext, "未找到消息盒子", Toast.LENGTH_LONG).show();
			this.finish();
		}
		
	}

	private void findView() {
		phoneNum = (EditText) findViewById(R.id.phoneEdt);
		verificationCode = (EditText) findViewById(R.id.codeEdt);
		btnGetCode = (Button) findViewById(R.id.btnGetCode);
		btnLogin = (Button) findViewById(R.id.btnLogin);
		btnGetCode.setOnClickListener(this);
		btnLogin.setOnClickListener(this);
		loginDialog = new AlertDialog.Builder(this).setTitle("您还没有登录，请先登录。")
				.setCancelable(false)
				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
						Intent intent=new Intent();
						intent.setAction("com.neteast.androidclient.newscenter.login");
						intent.putExtra("pkg", "com.neteast.androidclient.contact");
						intent.putExtra("cls", "com.neteast.androidclient.contact.activity.VerificationPhoneActivity");
						startActivity(intent);
						finish();
					}
				}).create();
		loginDialog.setCanceledOnTouchOutside(false);
	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btnGetCode: {
			String num = phoneNum.getText().toString().trim();
			if (num != null && !num.equals("")) {
					// TODO 通知服务器发送验证码到手机
					v.setEnabled(false);
					v.setBackgroundResource(R.drawable.btn_get_code_disabled);
					if (timer == null) {
						timer = new Timer();
					}
					timer.schedule(new TimerTask() {
						@Override
						public void run() {
							handler.sendEmptyMessage(UPDATE_TIME);
						}
					}, 0, 1000);
					Toast.makeText(VerificationPhoneActivity.this, "已发送验证码到手机，请查收",
							Toast.LENGTH_LONG).show();
			} else {
				Toast.makeText(VerificationPhoneActivity.this, "请输入正确的手机号码",
						Toast.LENGTH_LONG).show();
			}
			
			break;
		}
		case R.id.btnLogin: {
			String num = phoneNum.getText().toString().trim();
			String code = verificationCode.getText().toString().trim();
			if(num.equals("")){
				Toast.makeText(VerificationPhoneActivity.this, "电话号码不能为空",
						Toast.LENGTH_LONG).show();
			}else if(code.equals("")){
				Toast.makeText(VerificationPhoneActivity.this, "请输入验证码",
						Toast.LENGTH_LONG).show();
			}else{
				SharedPreferences.Editor editor = sharedPreferences.edit();
				editor.putBoolean("isVerificated", true);
				editor.commit();
				startActivity(new Intent(VerificationPhoneActivity.this,MainActivity.class));
				finish();
			}
			break;
		}
		}

	}
	protected static final int NEED_UPGRADE = 0;
	protected static final int DO_NOT_NEED_UPGRADE = 1;
	protected static final int UPGRADE_ERROR= 2;
	protected static final int UPDATE_TIME = 3;
	
	UpgradeInfo info = null;	
	
	static class UpgradeInfo{
		public int code;
		public String description;
		public int versioncode;
		public String url;
		public boolean must;
		public long size;
	}
	
	private void refreshUploadInfo(final String path){
		new Thread(new Runnable() {
			public void run() {
				try {
					URL url=new URL(path);
					XmlPullParser parser = Xml.newPullParser();
					parser.setInput(url.openStream(), "UTF-8");
					int event = parser.getEventType();
					while(event!=XmlPullParser.END_DOCUMENT){
						switch (event) {
						case XmlPullParser.START_DOCUMENT:
							info=new UpgradeInfo();
							break;
						case XmlPullParser.START_TAG:
							String tag = parser.getName();
							if ("code".equals(tag)){
								info.code=Integer.parseInt(parser.nextText());
							}else if("description".equals(tag)){
								info.description=parser.nextText();
							}else if("versioncode".equals(tag)){
								info.versioncode=Integer.parseInt(parser.nextText());
							}else if("url".equals(tag)){
								info.url=parser.nextText();
							}else if("must".equals(tag)){
								int b=Integer.parseInt(parser.nextText());
								info.must=b==1;
							}else if("size".equals(tag)) {
								info.size=Long.parseLong(parser.nextText());
							}
							break;
						}
						event=parser.next();
					}
					if (shouldUpload(info.versioncode)) {
						handler.sendEmptyMessage(NEED_UPGRADE);
					}else {
						handler.sendEmptyMessage(DO_NOT_NEED_UPGRADE);
					}
				} catch (Exception e) {
					Log.i("test", "get Upgrade info error",e);
					handler.sendEmptyMessage(UPGRADE_ERROR);
				}
			}
		}).start();
	}
	
	private boolean shouldUpload(int remoteVersioncode) throws NameNotFoundException {
		int localVersionCode=getPackageManager().getPackageInfo(getPackageName(), PackageManager.GET_ACTIVITIES).versionCode;
		return remoteVersioncode>localVersionCode;
	}
	
	private void showAppUploadWindow() {
		AlertDialog.Builder builder=new AlertDialog.Builder(this);
		builder.setTitle("版本升级");
		builder.setCancelable(false);
		builder.setMessage(info.description);
		builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog, int which) {
				startDownLoadService();
				dialog.dismiss();
				finish();
			}
		});
		if (!info.must) {
			builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface dialog, int which) {
					checkLoginState();
					dialog.dismiss();
				}
			});
		}
		builder.create().show();
	}
	
	private void startDownLoadService() {
		Intent intent=new Intent(this, DownLoadService.class);
		intent.putExtra("apk_url", info.url);
		intent.putExtra("size", info.size);
		startService(intent);
	}
}
